package devicelogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddDeviceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddDeviceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDeviceLogic {
	return &AddDeviceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddDeviceLogic) AddDevice(in *iotpb.AddDeviceReq) (*iotpb.AddDeviceResp, error) {
	device := in.GetParams()
	if device == nil || device.GetDeptId() == 0 || device.GetProductId() == 0 || device.GetName() == "" ||
		device.GetCreateUser() == "" || device.GetUpdateUser() == "" ||
		in.GetUserId() == 0 {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增设备失败：参数缺失"),
			tool.GetErrMsgFormat("insert device"), "params is not existed", in)
	}

	var data model.IotDevice
	_ = copier.Copy(&data, in.GetParams())

	// 保存数据
	_, err := l.svcCtx.IotDeviceModel.InsertEx(l.ctx, nil, []*model.IotDevice{&data})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError),
			tool.GetErrMsgFormat("insert device"), err, in)

	}

	return &iotpb.AddDeviceResp{}, nil
}
